﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using BookStore.Solution.BLL;
using BookStore.Solution.Entities;

namespace BookStore.Solution.Presentation
{
    public partial class FrmEntryBill : DevComponents.DotNetBar.OfficeForm
    {
        EntryBillManager EntryBillManager = new EntryBillManager();
        List<EntryBillDetail> listEntryBilldt = new List<EntryBillDetail>();
        List<EntryBillDetail> list = new List<EntryBillDetail>();
        public EntryBill NewEntryBill { get; set; }
        DataTable MyBillDetailtable = null;
        string Status = "";
        ProductManager products = new ProductManager();
        SupplierManager supplier = new SupplierManager();
        public string result { get; set; }
        EntryBillDetailManager entryBillDT = new EntryBillDetailManager();
        string name="";
        long uniprice = 0;
        public FrmEntryBill()
        {
            InitializeComponent();
            this.Status = "insert";
        }
      
        public FrmEntryBill(EntryBill entrybill)
        {
            InitializeComponent();
            this.NewEntryBill = entrybill;
            this.Status = "update";
        }
        public FrmEntryBill(EntryBill Entrybill, string status)
        {
            InitializeComponent();
            this.NewEntryBill = Entrybill;
            this.Status = "view";
        }
        private DataTable CreateTable()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("ProductID", Type.GetType("System.String"));
            dt.Columns.Add("ProductName", Type.GetType("System.String"));
            dt.Columns.Add("Quatity", Type.GetType("System.Int32"));
            dt.Columns.Add("UnitPrice", Type.GetType("System.Int64"));
            return dt;
        }
        private void FrmEntryBill_Load(object sender, EventArgs e)
        {
            cbbSupplier.DataSource = supplier.GetAll();
            cbbSupplier.DisplayMember = "SupplierName";
            cbbSupplier.ValueMember = "SupplierID";
            if (Status.CompareTo("update") == 0 || Status.CompareTo("view") == 0)
            {
                txtEmployeeID.Text = NewEntryBill.EmployeeID;
                txtlEntryBillID.Text = NewEntryBill.EntryBillID.ToString();
                txtEmployeeID.Text = NewEntryBill.EmployeeID;
                dtDay.Value = NewEntryBill.Date;
                LoadDataGridview(NewEntryBill);
                listEntryBilldt = GetTable();
                if (Status.CompareTo("update") == 0)
                {
                    ReturnQuantity();
                    list = GetTable();

                }
                if (Status.CompareTo("view") == 0)
                {
                    btnAdd.Enabled = false;
                    btnDelete.Enabled = false;
                    btnUpdate.Enabled = false;
                }
                txUnitPrice.Text = uniprice.ToString();
               GetTable();
            }
            else
            {
                MyBillDetailtable = CreateTable();
                txUnitPrice.Text = "0";
                txtEmployeeID.Text = AccountManager.CurrentAccount.EmployeeID;
            }
        }
        private void ReturnQuantity()
        {
            foreach (var item in listEntryBilldt)
            {
                products.UpdateProduct(item, 1);
            }
        }
        private List<EntryBillDetail> GetTable()
        {
            List<EntryBillDetail> entrydt = new List<EntryBillDetail>();
            for (int i = 0; i < dtgvListProduct.RowCount; i++)
            {
                EntryBillDetail b = new EntryBillDetail();
                b.EntryBillID = NewEntryBill.EntryBillID;
                b.ProductID = dtgvListProduct.Rows[i].Cells[0].Value.ToString();
           //     MessageBox.Show(dtgvListProduct.Rows[i].Cells[2].Value.ToString());
                b.Quatity = int.Parse(dtgvListProduct.Rows[i].Cells[2].Value.ToString());
                b.UnitPrice = long.Parse(dtgvListProduct.Rows[i].Cells[3].Value.ToString());
                b.Status = "Đang tồn tại";
                entrydt.Add(b);
            }
           return entrydt;
        }
        private void LoadDataGridview(EntryBill entrybill)
        {

            MyBillDetailtable = entryBillDT.SearchID(entrybill.EntryBillID);
            LoadData(MyBillDetailtable);
        }
         private void LoadData(DataTable table)
        {
            foreach (DataRow row in table.Rows)
            {
                dtgvListProduct.Rows.Add(row["ProductID"], name, row["Quatity"], row["UnitPrice"]);
            }
            if (this.Status.CompareTo("update") == 0 || this.Status.CompareTo("view") == 0)
            {
                for (int i = 0; i < dtgvListProduct.RowCount; i++)
                {
                    string a = dtgvListProduct.Rows[i].Cells[0].Value.ToString();
                    uniprice += int.Parse(dtgvListProduct.Rows[i].Cells[2].Value.ToString()) * long.Parse(dtgvListProduct.Rows[i].Cells[3].Value.ToString());
                    dtgvListProduct.Rows[i].Cells["ProductName"].Value = EntryBillManager.GetNameProduct(a);
                }
                
            }
        }

         private void btnAdd_Click(object sender, EventArgs e)
         {
             bool check = true;
             FrmEntryBillDetail frmdetail = new FrmEntryBillDetail();
             frmdetail.ShowDialog();
             if (this.Status.CompareTo("insert") == 0)
             {
                 if (frmdetail.newdetail != null)
                 {
                     for (int i = 0; i < dtgvListProduct.RowCount; i++)
                     {
                         if (dtgvListProduct.Rows[i].Cells[0].Value.ToString().Equals(frmdetail.newdetail.ProductID))
                         {
                             dtgvListProduct.Rows[i].Cells[2].Value = int.Parse(dtgvListProduct.Rows[i].Cells[2].Value.ToString()) + frmdetail.newdetail.Quatity;
                             txUnitPrice.Text = (int.Parse(txUnitPrice.Text) + frmdetail.newdetail.Quatity * frmdetail.newdetail.UnitPrice).ToString();
                             check = false;
                         }
                     }
                     if (check)
                     {
                         name = frmdetail.productName;
                         txUnitPrice.Text = (int.Parse(txUnitPrice.Text) + frmdetail.newdetail.Quatity * frmdetail.newdetail.UnitPrice).ToString();
                         InsertDatagridview(frmdetail.newdetail);
                     }
                 }
             }
             if (this.Status.CompareTo("update") == 0)
             {
                 if (frmdetail.newdetail != null)
                 {
                     for (int i = 0; i < dtgvListProduct.RowCount; i++)
                     {
                         if (dtgvListProduct.Rows[i].Cells[0].Value.ToString().Equals(frmdetail.newdetail.ProductID))
                         {
                             dtgvListProduct.Rows[i].Cells[2].Value = int.Parse(dtgvListProduct.Rows[i].Cells[2].Value.ToString()) + frmdetail.newdetail.Quatity;
                             for (int j = 0; j < listEntryBilldt.Count; j++)
                             {
                                 if (listEntryBilldt[j].ProductID.CompareTo(frmdetail.newdetail.ProductID) == 0)
                                 {
                                     listEntryBilldt[j].Quatity += frmdetail.newdetail.Quatity;
                                     txUnitPrice.Text= (int.Parse(txUnitPrice.Text)+frmdetail.newdetail.Quatity * frmdetail.newdetail.UnitPrice).ToString();
                                     check = false;
                                     break;
                                 }
                             }
                         }

                     }
                     if (check)
                     {
                         name = frmdetail.productName;
                         txUnitPrice.Text = (int.Parse(txUnitPrice.Text) + frmdetail.newdetail.Quatity * frmdetail.newdetail.UnitPrice).ToString();
                         InsertDatagridview(frmdetail.newdetail);
                         listEntryBilldt.Add(frmdetail.newdetail);
                     }

                 }
             }
         }
         private void InsertDatagridview(EntryBillDetail entryBilldetail)
         {
             dtgvListProduct.Rows.Add(entryBilldetail.ProductID, name, entryBilldetail.Quatity, entryBilldetail.UnitPrice);
         }

         private void btnDelete_Click(object sender, EventArgs e)
         {
             if (dtgvListProduct.SelectedRows.Count > 0)
             {
                 if (this.Status.CompareTo("insert") == 0)
                 {
                     txUnitPrice.Text = (int.Parse(txUnitPrice.Text) - int.Parse(dtgvListProduct.Rows[dtgvListProduct.CurrentRow.Index].Cells[2].Value.ToString()) * long.Parse(dtgvListProduct.Rows[dtgvListProduct.CurrentRow.Index].Cells[3].Value.ToString())).ToString();
                     dtgvListProduct.Rows.RemoveAt(dtgvListProduct.CurrentRow.Index);
                 }
                 if (this.Status.CompareTo("update") == 0)
                 {
                     foreach (var item in listEntryBilldt)
                     {
                         if (dtgvListProduct.SelectedRows[0].Cells[0].Value.ToString().CompareTo(item.ProductID) == 0)
                         {
                             item.Status = "Đã xóa";
                             break;
                         }
                     }
                     txUnitPrice.Text = (long.Parse(txUnitPrice.Text) - (int.Parse(dtgvListProduct.Rows[dtgvListProduct.CurrentRow.Index].Cells[2].Value.ToString()) * long.Parse(dtgvListProduct.Rows[dtgvListProduct.CurrentRow.Index].Cells[3].Value.ToString()))).ToString();
                     dtgvListProduct.Rows.RemoveAt(dtgvListProduct.CurrentRow.Index);
                 }
             }
             else
                 MessageBox.Show("Bạn chưa chọn phiếu nhập chi tiết nào để xóa", "Thống báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
         }
         private List<string> GetBillDetail()
         {
             List<string> bdt = new List<string>();
             bdt.Add(dtgvListProduct.SelectedRows[0].Cells[0].Value.ToString());
             bdt.Add(dtgvListProduct.SelectedRows[0].Cells[1].Value.ToString());
             bdt.Add(dtgvListProduct.SelectedRows[0].Cells[2].Value.ToString());
             bdt.Add(dtgvListProduct.SelectedRows[0].Cells[3].Value.ToString());
             return bdt;
         }
         private void btnUpdate_Click(object sender, EventArgs e)
         {
             if (dtgvListProduct.SelectedRows.Count > 0)
             {
                 List<string> bdt = GetBillDetail();
                 FrmEntryBillDetail frmdetail = new FrmEntryBillDetail(bdt);
                 frmdetail.ShowDialog();
                 if (frmdetail.newdetail != null)
                 {
                     for (int i = 0; i < dtgvListProduct.RowCount; i++)
                     {
                         if (dtgvListProduct.Rows[i].Cells[0].Value.ToString().Equals(frmdetail.newdetail.ProductID))
                         {
                             txUnitPrice.Text = (long.Parse(txUnitPrice.Text) + (frmdetail.newdetail.Quatity * frmdetail.newdetail.UnitPrice) - (int.Parse(dtgvListProduct.Rows[dtgvListProduct.CurrentRow.Index].Cells[2].Value.ToString()) * long.Parse(dtgvListProduct.Rows[dtgvListProduct.CurrentRow.Index].Cells[3].Value.ToString()))).ToString();
                             dtgvListProduct.Rows[i].Cells[2].Value = frmdetail.newdetail.Quatity;
                         }
                     }
                     if (this.Status.CompareTo("update") == 0)
                     {
                         for (int i = 0; i < listEntryBilldt.Count; i++)
                         {
                             if (listEntryBilldt[i].ProductID.CompareTo(frmdetail.newdetail.ProductID) == 0)
                             {
                                 txUnitPrice.Text = (long.Parse(txUnitPrice.Text) + (frmdetail.newdetail.Quatity * frmdetail.newdetail.UnitPrice) - (int.Parse(dtgvListProduct.Rows[dtgvListProduct.CurrentRow.Index].Cells[2].Value.ToString()) * long.Parse(dtgvListProduct.Rows[dtgvListProduct.CurrentRow.Index].Cells[3].Value.ToString()))).ToString();
                                 listEntryBilldt[i].Quatity = frmdetail.newdetail.Quatity;
                             }
                         }
                     }
                 }
             }
             else
                 MessageBox.Show("Bạn chưa chọn hóa đơn chi tiết cần sửa", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
         }
         private EntryBill GetBill()
         {
             EntryBill b = new EntryBill();

             b.EmployeeID =AccountManager.CurrentAccount.EmployeeID;
             b.Date = dtDay.Value;
             b.Status = "Đang tồn tại";
             b.SupplierID = cbbSupplier.SelectedValue.ToString();
             return b;
         }
         private bool checkValidation()
         {
             if (dtDay.Value.Year < 2013)
             {
                 MessageBox.Show("Năm nhập vào phải lớn hơn 2013", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                 lblDay.ForeColor = Color.Red;
                 return false;
             }
             if (dtgvListProduct.RowCount == 0)
             {
                 MessageBox.Show("Bạn chưa nhập sản phẩm nào cho hóa đơn", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                 return false;
             }
             return true;
         }
         private void btnOK_Click(object sender, EventArgs e)
         {
             if (checkValidation())
             {
                 if (this.Status.CompareTo("insert") == 0)
                 {
                     if (dtgvListProduct.RowCount > 0)
                     {
                         NewEntryBill = GetBill();
                         int billid = EntryBillManager.Insert(NewEntryBill);
                         for (int i = 0; i < dtgvListProduct.RowCount; i++)
                         {
                             Product p;
                             EntryBillDetail billdetails = new EntryBillDetail();
                             billdetails.ProductID = dtgvListProduct.Rows[i].Cells[0].Value.ToString();
                             billdetails.EntryBillID = billid;
                             billdetails.Quatity = int.Parse(dtgvListProduct.Rows[i].Cells[2].Value.ToString());
                             billdetails.UnitPrice = long.Parse(dtgvListProduct.Rows[i].Cells[3].Value.ToString());
                             billdetails.Status = "Đang tồn tại";
                             entryBillDT.InsertBillDetail(billdetails);
                             p = products.SearchByID(billdetails.ProductID);
                             p.Quatity = p.Quatity + billdetails.Quatity;
                             products.UpdateProduct(p);                          
                         }
                         
                     }
                 }
                 if (this.Status.CompareTo("update") == 0)
                 {
                     foreach (var item in listEntryBilldt)
                     {
                         if (item.Status.CompareTo("Chưa tồn tại") == 0)
                         {
                             item.EntryBillID = NewEntryBill.EntryBillID;
                             item.Status = "Đang tồn tại";
                             entryBillDT.InsertBillDetail(item);
                         }
                         else
                             entryBillDT.UpdateStatus(item);
                         products.UpdateProduct(item, -1);
                     }
                     NewEntryBill.Date = dtDay.Value;
                     NewEntryBill.SupplierID = cbbSupplier.SelectedValue.ToString();
                     result = EntryBillManager.UpdateStatus(NewEntryBill);
                     MessageBox.Show(result, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                 }
              
                 this.Status = "close";
                 Close();
             }// doi tr xiu
         }
         private void btnCancel_Click(object sender, EventArgs e)
         {

             DialogResult dl = MessageBox.Show("Bạn muốn hủy các thao tác trên phiếu nhập", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
             if (dl == DialogResult.Yes)
             {
                 foreach (var item in list)
                 {
                     products.UpdateProduct(item, -1);
                 }
                 this.Status = "close";
                 Close();
             }
         }

         private void FrmEntryBill_FormClosed(object sender, FormClosedEventArgs e)
         {
             if (this.Status.CompareTo("close") != 0)
             {
                 DialogResult dl = MessageBox.Show("Bạn muốn hủy các thao tác trên phiếu nhập", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                 if (dl == DialogResult.Yes)
                 {
                     foreach (var item in list)
                     {
                         products.UpdateProduct(item, -1);
                     }
                     Close();
                 }
             }
         }
    }
}